package com.inclass.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.tinygroup.htmlparser.HtmlDocument;
import org.tinygroup.htmlparser.node.HtmlNode;
import org.tinygroup.htmlparser.parser.HtmlStringParser;
import org.tinygroup.parser.filter.FastNameFilter;
import org.tinygroup.parser.filter.QuickNameFilter;

import com.inclass.security.Md5PwdEncoder;

@Controller
public class TestController {

    @RequestMapping("/index")
	public String index(){
		return "index";
	}
    @RequestMapping("/love")
	public String index2(){
    	System.out.println("!!!!!!!!");
		return "index";
	}
    @RequestMapping("/login")
	public String login(ModelMap model){
    	model.put("msg", "/login");
    	System.out.println("!!!!!!!!");
		return "index";
	}
    @RequestMapping("/user/love")
	public String userlove(ModelMap model){
    	model.put("msg", "/user/love");
    	System.out.println("!!!!!!!!");
		return "index";
	}
    @RequestMapping("/403.do")
	public String f403(ModelMap model){
    	model.put("msg", "/403.do");
    	System.out.println("!!/403.do!!!!!!");
		return "index";
	}
    @RequestMapping("/testcas")
	public String testcas(ModelMap model){
    	model.put("msg", "/testcas");
    	System.out.println("!!!!testcas!!!");
		return "index";
	}
    @RequestMapping("/casFailure")
	public String casFailure(ModelMap model){
    	model.put("msg", "/casFailure");
    	System.out.println("!!!!!!!casFailure!");
		return "index";
	}
    @RequestMapping("/mlogin")
    public String monitorLogin(HttpServletRequest request, HttpServletResponse response){
    	CloseableHttpClient client = HttpClientBuilder.create()
    			.disableRedirectHandling()
    			.build();  
    	String url = "http://cas0.hdu.edu.cn/cas/login?service=http://192.168.191.3:8080/JustServlet/docas";
		HttpGet httpGet = new HttpGet(url);
		HttpClientContext context = HttpClientContext.create();  
		String ticket = null;
    	try {
			CloseableHttpResponse closeableHttpResponse = client.execute(httpGet,context);
			int status = closeableHttpResponse.getStatusLine().getStatusCode();
			System.out.println(status);
			Header[] headers = closeableHttpResponse.getHeaders(HttpHeaders.CONTENT_TYPE);  
			String bodyString = EntityUtils.toString(closeableHttpResponse.getEntity());
			CookieStore c = context.getCookieStore();
			System.out.println("cookie1___________"+c.toString());

			HtmlNode node = TestController.getForm(bodyString);
			String loginErrCnt = TestController.getInputValue(node, "loginErrCnt");
			String service = TestController.getInputValue(node, "service");
			String serviceName = TestController.getInputValue(node, "serviceName");
			String lt = TestController.getInputValue(node, "lt");
			String encodedService = TestController.getInputValue(node, "encodedService");
			
			
			url="http://cas0.hdu.edu.cn/cas/login";
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			String username = "11225104";
			String password = md5PwdEncoder.encodePassword("zch19911107");
			formparams.add(new BasicNameValuePair("username", username));  
			formparams.add(new BasicNameValuePair("password", password));  
			formparams.add(new BasicNameValuePair("loginErrCnt", loginErrCnt));  
			formparams.add(new BasicNameValuePair("service", service));  
			formparams.add(new BasicNameValuePair("serviceName", serviceName));  
			formparams.add(new BasicNameValuePair("lt", lt));  
			formparams.add(new BasicNameValuePair("encodedService", encodedService));  
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);  
			httpPost.setEntity(entity);
			
			
			CloseableHttpResponse closeableHttpResponse2 = client.execute(httpPost, context);
			String bodyString2 = EntityUtils.toString(closeableHttpResponse2.getEntity());
			System.out.println(bodyString2);
			CookieStore c2 = context.getCookieStore();
			System.out.println("cookie 2_________"+c2.toString());
			ticket = TestController.getTicket(bodyString2);
//			String ticket = TestController.get
			System.out.println("#############" + ticket);
//			HtmlNode node2 = TestController.getForm(content);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "redirect:/docas?ticket="+ticket;
	}
    public static void main(String[] args) {
    	CloseableHttpClient client = HttpClientBuilder.create()
    			.disableRedirectHandling()
    			.build();  
    	String url = "http://cas0.hdu.edu.cn/cas/login?service=http://192.168.191.3:8080/JustServlet/docas";
		HttpGet httpGet = new HttpGet(url);
		HttpClientContext context = HttpClientContext.create();  
    	try {
			CloseableHttpResponse closeableHttpResponse = client.execute(httpGet,context);
			int status = closeableHttpResponse.getStatusLine().getStatusCode();
			System.out.println(status);
			Header[] headers = closeableHttpResponse.getHeaders(HttpHeaders.CONTENT_TYPE);  
			String bodyString = EntityUtils.toString(closeableHttpResponse.getEntity());
			CookieStore c = context.getCookieStore();
			System.out.println(c.toString());

			HtmlNode node = TestController.getForm(bodyString);
			String loginErrCnt = TestController.getInputValue(node, "loginErrCnt");
			String service = TestController.getInputValue(node, "service");
			String serviceName = TestController.getInputValue(node, "serviceName");
			String lt = TestController.getInputValue(node, "lt");
			String encodedService = TestController.getInputValue(node, "encodedService");
			
			
			url="http://cas0.hdu.edu.cn/cas/login";
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			String username = "11225104";
			String password = md5PwdEncoder.encodePassword("zch19911107");
			formparams.add(new BasicNameValuePair("username", username));  
			formparams.add(new BasicNameValuePair("password", password));  
			formparams.add(new BasicNameValuePair("loginErrCnt", loginErrCnt));  
			formparams.add(new BasicNameValuePair("service", service));  
			formparams.add(new BasicNameValuePair("service", serviceName));  
			formparams.add(new BasicNameValuePair("service", lt));  
			formparams.add(new BasicNameValuePair("service", encodedService));  
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);  
			httpPost.setEntity(entity);
			
			
			CloseableHttpResponse closeableHttpResponse2 = client.execute(httpPost, context);
			String bodyString2 = EntityUtils.toString(closeableHttpResponse2.getEntity());
			System.out.println(bodyString2);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
    public static HtmlNode getForm(String content) {
    	HtmlDocument document = new HtmlStringParser().parse(content);
    	HtmlNode node = document.getRoot();
        QuickNameFilter<HtmlNode> nodeFilter = new QuickNameFilter<HtmlNode>(node);
        nodeFilter.setNodeName("form");
        nodeFilter.setIncludeAttribute("class", "login_form");
        return nodeFilter.getNode();
	}
    public static String getTicket(String html){
    	
    	HtmlDocument document = new HtmlStringParser().parse(html);
    	HtmlNode node = document.getRoot();
    	QuickNameFilter<HtmlNode> nodeFilter = new QuickNameFilter<HtmlNode>(node);
    	nodeFilter.setNodeName("a");
    	HtmlNode re = nodeFilter.findNode();
    	String result  = re.getAttribute("href");
    	return result.substring(result.indexOf("=")+1);
    }
    
    public static String getInputValue(HtmlNode node,String name) {
        FastNameFilter<HtmlNode> filter = new FastNameFilter<HtmlNode>(node);
        filter.setNodeName("input");
        filter.setIncludeAttribute("name", name);
        HtmlNode inputNode = filter.findNode();
        String value = inputNode.getAttribute("value");
		return value;
	}
}
